// DOM 元素选择
const aboutSection = document.getElementById('about');
const projectsSection = document.getElementById('projects');
const contactSection = document.getElementById('contact');
const navLinks = document.querySelectorAll('nav ul li a');
const projectItems = document.querySelectorAll('.project-item');

// 滚动动画效果
function animateOnScroll() {
    const sections = [aboutSection, projectsSection, contactSection];
    
    sections.forEach(section => {
        const sectionTop = section.getBoundingClientRect().top;
        const windowHeight = window.innerHeight;
        
        if (sectionTop < windowHeight * 0.75) {
            section.style.opacity = '1';
            section.style.transform = 'translateY(0)';
        }
    });
}

// 初始化动画效果
function initAnimations() {
    [aboutSection, projectsSection, contactSection].forEach(section => {
        section.style.opacity = '0';
        section.style.transform = 'translateY(20px)';
        section.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    });
    
    // 立即检查一次，确保首屏内容显示
    animateOnScroll();
}

// 平滑滚动
function smoothScroll(e) {
    e.preventDefault();
    const targetId = this.getAttribute('href');
    const targetElement = document.querySelector(targetId);
    
    window.scrollTo({
        top: targetElement.offsetTop - 80,
        behavior: 'smooth'
    });
}

// 项目卡片交互效果
function addProjectInteractions() {
    projectItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.backgroundColor = '#f0f0f0';
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.backgroundColor = '#f9f9f9';
        });
    });
}

// 计算器功能实现
function initCalculator() {
    const calculatorDisplay = document.getElementById('calculator-display');
    const numberButtons = document.querySelectorAll('[data-number]');
    const operationButtons = document.querySelectorAll('[data-operation]');
    const clearButton = document.querySelector('[data-operation="clear"]');
    const equalButton = document.querySelector('[data-operation="equal"]');
    
    let firstOperand = '';
    let waitingForSecondOperand = false;
    let currentOperation = null;
    
    // 更新显示
    function updateDisplay(number) {
        if (waitingForSecondOperand) {
            calculatorDisplay.textContent = number;
            waitingForSecondOperand = false;
        } else {
            calculatorDisplay.textContent = calculatorDisplay.textContent === '0' ? number : calculatorDisplay.textContent + number;
        }
    }
    
    // 处理数字输入
    numberButtons.forEach(button => {
        button.addEventListener('click', () => {
            const number = button.textContent;
            if (number === '.' && calculatorDisplay.textContent.includes('.')) return;
            updateDisplay(number);
        });
    });
    
    // 处理操作符
    operationButtons.forEach(button => {
        button.addEventListener('click', () => {
            const operation = button.dataset.operation;
            if (operation === 'clear') {
                // 归0功能
                calculatorDisplay.textContent = '0';
                firstOperand = '';
                waitingForSecondOperand = false;
                currentOperation = null;
                return;
            }
            
            if (operation === 'equal' && currentOperation) {
                // 计算结果
                const secondOperand = calculatorDisplay.textContent;
                calculatorDisplay.textContent = calculate(firstOperand, secondOperand, currentOperation);
                currentOperation = null;
                firstOperand = calculatorDisplay.textContent;
                waitingForSecondOperand = true;
                return;
            }
            
            // 其他操作符
            if (currentOperation) {
                // 如果已经有操作符，先计算
                const secondOperand = calculatorDisplay.textContent;
                firstOperand = calculate(firstOperand, secondOperand, currentOperation);
                calculatorDisplay.textContent = firstOperand;
            } else {
                firstOperand = calculatorDisplay.textContent;
            }
            
            waitingForSecondOperand = true;
            currentOperation = operation;
        });
    });
    
    // 执行计算
    function calculate(firstOperand, secondOperand, operation) {
        const first = parseFloat(firstOperand);
        const second = parseFloat(secondOperand);
        
        if (isNaN(first) || isNaN(second)) return '0';
        
        let result;
        switch (operation) {
            case 'add':
                result = first + second;
                break;
            case 'subtract':
                result = first - second;
                break;
            case 'multiply':
                result = first * second;
                break;
            case 'divide':
                if (second === 0) return 'Error';
                result = first / second;
                break;
            case 'modulo':
                result = first % second;
                break;
            default:
                return secondOperand;
        }
        
        // 处理小数位数
        return parseFloat(result.toFixed(8));
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化语言功能
    if (window.initLanguage) {
        initLanguage();
    }
    
    initAnimations();
    addProjectInteractions();
    
    // 计算器弹出窗口逻辑
    const calculatorPopup = document.getElementById('calculator-popup');
    const closeButton = document.querySelector('.calculator-popup-close');
    const calculatorImage = document.getElementById('calculator-image');
    
    // 点击计算器图片显示弹出窗口
    if (calculatorImage && calculatorPopup) {
        calculatorImage.addEventListener('click', function() {
            calculatorPopup.classList.add('active');
        });
    }
    
    // 关闭按钮点击事件
    if (closeButton) {
        closeButton.addEventListener('click', function() {
            if (calculatorPopup) {
                calculatorPopup.classList.remove('active');
            }
        });
    }
    
    // 点击弹出窗口外部关闭
    if (calculatorPopup) {
        calculatorPopup.addEventListener('click', function(e) {
            if (e.target === calculatorPopup) {
                calculatorPopup.classList.remove('active');
            }
        });
    }
    
    // 初始化计算器
    initCalculator();
    
    // 联系表单处理
    const contactForm = document.getElementById('contact-form');
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const message = document.getElementById('message').value;
            
            // 简单的表单验证
            if (!name || !email || !message) {
                alert('请填写所有必填字段！');
                return;
            }
            
            // 邮箱格式验证
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                alert('请输入有效的邮箱地址！');
                return;
            }
            
            // 模拟表单提交成功
            alert('消息发送成功！我会尽快回复您。');
            
            // 清空表单
            contactForm.reset();
        });
    }
    
    // 添加滚动事件监听
    window.addEventListener('scroll', animateOnScroll);
    
    // 添加导航链接点击事件
    navLinks.forEach(link => {
        link.addEventListener('click', smoothScroll);
    });
    
    // 显示页面加载完成的提示
    console.log('个人作品集网站加载完成');
});